<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="商品名" prop="name">
        <el-input v-model="dataForm.name" placeholder="商品名"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="商品描述"></el-input>
      </el-form-item>
      <el-form-item label="商品详情" prop="detail">
        <el-input v-model="dataForm.detail" placeholder="商品详情"></el-input>
      </el-form-item>
      <el-form-item label="上传图片" prop="imgUrl">
        <el-upload
          class="upload-demo"
          action="#"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :http-request="uploadImg"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList">
          <img width="100px" height="100px" v-if="dataForm.imgUrl" :src="'http://localhost:8080/renren-fast' + dataForm.imgUrl"/>
          <br v-if="dataForm.imgUrl">
          <el-button size="small" type="primary">点击上传</el-button>
          <!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
        </el-upload>
      </el-form-item>
      <el-form-item label="商品单价" prop="price">
        <el-input v-model="dataForm.price" placeholder="商品单价"></el-input>
      </el-form-item>
      <el-form-item label="商品单位" prop="unit">
        <el-input v-model="dataForm.unit" placeholder="商品单位"></el-input>
      </el-form-item>
      <el-form-item label="商品库存" prop="quantity">
        <el-input v-model="dataForm.quantity" placeholder="商品库存"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="dataForm.categoryId" placeholder="请选择商品分类">
          <el-option v-for="option in options" :key="option.categoryId" :value="option.categoryId"
                     :label="option.categoryName"></el-option>
        </el-select>
      </el-form-item>
      <!--    <el-form-item label="上架时间" prop="shelfTime">
            <el-input v-model="dataForm.shelfTime" placeholder="上架时间"></el-input>
          </el-form-item>
          <el-form-item label="浏览量" prop="viewCount">
            <el-input v-model="dataForm.viewCount" placeholder="浏览量"></el-input>
          </el-form-item>
          <el-form-item label="销量" prop="saleCount">
            <el-input v-model="dataForm.saleCount" placeholder="销量"></el-input>
          </el-form-item>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      type: 'product',
      fileList: [],
      visible: false,
      options: [],
      dataForm: {
        id: 0,
        name: '',
        description: '',
        detail: '',
        imgUrl: '',
        price: '',
        unit: '',
        quantity: '',
        categoryId: ''
      },
      dataRule: {
        name: [
          {required: true, message: '商品名不能为空', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '商品描述不能为空', trigger: 'blur'}
        ],
        detail: [
          {required: true, message: '商品详情不能为空', trigger: 'blur'}
        ],
        imgUrl: [
          {required: true, message: '图片URL不能为空', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '商品单价不能为空', trigger: 'blur'}
        ],
        unit: [
          {required: true, message: '商品单位不能为空', trigger: 'blur'}
        ],
        quantity: [
          {required: true, message: '商品库存不能为空', trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: '商品类型不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    init (id) {
      // 加载下拉框选项
      this.$http({
        url: this.$http.adornUrl(`/manage/productcategory/queryAllCategory`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.options = []
          data.categorys.forEach(item => {
            this.options.push({
              categoryId: item.id,
              categoryName: item.name
            })
          })
        }
      })
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.fileList = [];
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/manage/product/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.product.name
              this.dataForm.description = data.product.description
              this.dataForm.detail = data.product.detail
              this.dataForm.imgUrl = data.product.imgUrl
              const parts = data.product.imgUrl.split('/')
              this.fileList.push({
                name: parts[parts.length - 1],
                url: 'http://localhost:8080/renren-fast' + data.product.imgUrl
              })
              this.dataForm.price = data.product.price
              this.dataForm.unit = data.product.unit
              this.dataForm.quantity = data.product.quantity
              this.dataForm.categoryId = data.product.categoryId
            }
          })
        }
      })
    },
    uploadImg (item) {
      const fileObj = item.file
      console.log(fileObj.name)
      // FormData 对象
      const form01 = new FormData()
      // 文件对象
      form01.append('file', fileObj)
      this.$http({
        url: this.$http.adornUrl(`/manage/file/upload/${this.type}`),
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: form01
      }).then(({data}) => {
        console.log(data)
        if (data && data.code === 0) {
          this.$message({
            message: '上传成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.fileList.push({
                name: fileObj.name,
                url: 'http://localhost:8080/renren-fast' + data.fileInfo
              })
              this.dataForm.imgUrl = data.fileInfo
            }
          })
        } else {
          this.$message({
            message: '上传失败',
            type: 'warning',
            duration: 1500,
            onClose: () => {
            }
          })
        }
      }).catch(() => {
        this.$message.error('异常错误')
      })
    },
    handleRemove (item, fileList) {
      console.log(item, fileList)
      var filename = item.name
      console.log('删除文件名：', filename)
      this.$http({
        url: this.$http.adornUrl(`/manage/file/delete/${this.type}`),
        method: 'post',
        data: this.$http.adornData({
          'filename': filename
        })
      }).then(({data}) => {
        console.log(data)
        if (data && data.code === 0) {
          this.$message({
            message: '移除成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.fileList = this.fileList.filter(item => item.name !== filename)
              this.dataForm.imgUrl = ''
            }
          })
        } else {
          this.$message({
            message: '移除失败',
            type: 'warning',
            duration: 1500,
            onClose: () => {
            }
          })
        }
      }).catch(() => {
        this.$message.error('异常错误')
      })
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 表单提交
    dataFormSubmit () {
      console.log('提交表单：',this.dataForm)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/manage/product/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'name': this.dataForm.name,
              'description': this.dataForm.description,
              'detail': this.dataForm.detail,
              'imgUrl': this.dataForm.imgUrl,
              'price': this.dataForm.price,
              'unit': this.dataForm.unit,
              'quantity': this.dataForm.quantity,
              'categoryId': this.dataForm.categoryId
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
